package com.yc.atm;

import java.util.ArrayList;
import java.util.List;

public class Bank {
    private List<BankAccount> accounts = new ArrayList<BankAccount>();

    public Bank() {
        for (int i=1;i<10;i++) {
            accounts.add(new BankAccount(i, 10));
        }
    }

    //查询无需加锁
    public BankAccount search(int id) throws Exception {
       for(BankAccount ba:accounts){
           if (ba.getId()==id) {
               return  ba;
           }
       }
        throw new Exception("无此账户"+id);
    }


    //存款加锁
    public BankAccount deposite(int id,double money) throws Exception {
        BankAccount ba = search(id);
        synchronized (ba){ //将锁粒度细化
            ba.setBalance(ba.getBalance()+money);
        }
        return ba;
    }


    //取款
    public BankAccount withdraw(int id,double money) throws Exception {
        BankAccount ba = search(id);
        synchronized (ba){
            if (money>ba.getBalance()) {
                throw new Exception("账户余额不足");
            }
            ba.setBalance(ba.getBalance()-money);
        }
        return ba;
    }
}
